import React, { createContext, useContext, useEffect, useState } from 'react';

const AuthContext = createContext();

export function AuthProvider({ children }) {
  const [userInfo, setUserInfo] = useState(null);
  const [token, setToken] = useState(null);
  const [isValidToken, setIsValidToken] = useState(false);

  useEffect(() => {
    const savedUserInfo = localStorage.getItem('userInfo');
    const savedToken = localStorage.getItem('token');

    if (savedUserInfo && savedToken) {
      setUserInfo(JSON.parse(savedUserInfo));
      setToken(savedToken);
      setIsValidToken(true);
    }

    const tokenRefreshInterval = setInterval(async () => {
      if (token) {
        try {
          const response = await fetch('/api/token/refresh', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${token}`
            }
          });

          if (response.ok) {
            const refreshedToken = await response.json();
            setToken(refreshedToken.accessToken);
            localStorage.setItem('token', refreshedToken.accessToken);
          } else {
            setUserInfo(null);
            setToken(null);
            setIsValidToken(false);
            localStorage.removeItem('userInfo');
            localStorage.removeItem('token');
          }
        } catch (error) {
          setUserInfo(null);
          setToken(null);
          setIsValidToken(false);
          localStorage.removeItem('userInfo');
          localStorage.removeItem('token');
          console.error('Token refresh failed:', error);
        }
      }
    }, 10 * 60 * 1000);

    return () => {
      clearInterval(tokenRefreshInterval);
    };
  }, [token]);

  const login = (user, authToken) => {
    setUserInfo(user);
    setToken(authToken);
    setIsValidToken(true);
    localStorage.setItem('userInfo', JSON.stringify(user));
    localStorage.setItem('token', authToken);
  };

  const logout = () => {
    setUserInfo(null);
    setToken(null);
    setIsValidToken(false);
    localStorage.removeItem('userInfo');
    localStorage.removeItem('token');
  };

  return (
    <AuthContext.Provider value={{ userInfo, token, isValidToken, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
